#include <iostream>
#include <cstdio>
#include <opencv2/opencv.hpp>
#include <opencv2/highgui/highgui.hpp>
using namespace std;
using namespace cv;
#define Red
const char videopath[] = "D://Sources//moveCar1.avi";

VideoCapture video;

void videolink();
void video_process();
void frame_process(const Mat &);

int main()
{
	videolink();
	video_process();
	return 0;
}


void frame_process(const Mat& frame)
{
	Mat channel[3]; split(frame, channel);
#ifdef Red
	Mat tar = -1.0*channel[0] -0*channel[1] +2.0*channel[2];
#else
	Mat tar = +2.0*channel[0] -0*channel[1] -1.0*channel[2];
#endif
	threshold(tar, tar, 80, 255, THRESH_BINARY);

	erode(tar, tar, getStructuringElement(MORPH_ELLIPSE, Size(5, 5), Point(2, 2)));
	dilate(tar, tar, getStructuringElement(MORPH_RECT, Size(7, 7), Point(3, 3)));

	vector<vector<Point>> contours;
	findContours(tar, contours, RETR_TREE, CHAIN_APPROX_NONE);

	//draw
	Mat tar_con(tar.rows, tar.cols, CV_8UC3, Scalar(255, 255, 255));
	drawContours(tar_con, contours, -1, Scalar(0,0,255));
	for (int i = 0; i < contours.size(); i++)
	{
		if (contours[i].size() < 6) continue;
		RotatedRect elli = fitEllipse(contours[i]);
		if (MAX(elli.size.height, elli.size.width) < MIN(elli.size.height, elli.size.width) * 3) 
			continue;
		if (fabs(elli.angle - 90) < 45) continue;
		//printf("angle: %.4f\n", elli.angle - 90);
		ellipse(tar_con, elli, Scalar(255, 0, 0));
	}

	imshow("after process", tar);
	imshow("contours", tar_con);
}
void video_process()
{
	Mat nowframe;
	
	while (video.read(nowframe))
	{
		imshow("nowvideo", nowframe);
		frame_process(nowframe);
		waitKey(33);
	}
	cout << "video finished" << endl;
	return ;
}
void videolink()
{
	video.open(videopath);
	if (!video.isOpened())
	{
		cout << "video not found" << endl;
		exit(1);
	}
}